from rest_framework import status,response
from django.shortcuts import get_object_or_404
from rest_framework.decorators import action

from utils.custom_log   import log_start
logger = log_start('Mixins')


class MultipleDestroyMixin(object):
    """
    用于批量删除模型实例
    """
    def __init__(self,queryset):
        self.queryset = queryset

    def get_serializer(self, *args, **kwargs):
        serializer_class = self.get_serializer_class()
        kwargs.setdefault('context', self.get_serializer_context())
        if isinstance(self.request.data, list):
            return serializer_class(many=True, *args, **kwargs)
        else:
            return serializer_class(*args, **kwargs)
    
    # delete /api/system/permissions/multiple_delete/?ids=10,11
    @action(methods=['delete'], detail=False)
    def multiple_delete(self, request,  *args, **kwargs):
        delete_ids = request.query_params.get('ids', None)
        logger.info(f'批量删除id:{delete_ids}')
        if not delete_ids:
            return response.Response(data={'detail': '参数错误, ?ids=x,x 为必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        
        delete_ids = delete_ids.split(',')
        queryset = self.get_queryset()
        del_queryset = queryset.filter(id__in=delete_ids)
        if len(delete_ids) != del_queryset.count():
            return response.Response(data={'detail': '删除数据不存在'}, status=status.HTTP_400_BAD_REQUEST)
        del_queryset.delete()
        return response.Response(status=status.HTTP_204_NO_CONTENT)
        
        # for id in delete_ids.split(','):
        #     if  id.isdigit():
        #         get_object_or_404(self.queryset, pk=int(id)).delete()





